package com.delayqueue.common.netty;

import com.delayqueue.common.util.NettyMessageUtil;
import io.netty.channel.ChannelHandlerContext;

public class ConnectCache {

    private Node node;

    public void sendMessage(NettyMessage nettyMessage) {
        if (node != null) {
            ChannelHandlerContext context = node.getChannelHandlerContext();
            NettyMessageUtil.send(context, nettyMessage);
        }
    }

    public void change(Node node) {
        Node old = this.node;
        this.node = node;
        if (old != null) {
            ChannelHandlerContext context = old.getChannelHandlerContext();
            context.channel().close();
            context.close();
        }
    }

    public void disconnect() {
        if (node != null) {
            ChannelHandlerContext context = node.getChannelHandlerContext();
            context.channel().close();
            context.close();
        }
    }

    public Address getRemoteAddress() {
        return NettyUtil.getRemoteAddress(node.getChannelHandlerContext());
    }
}
